import pytest
import requests

from api.api_register_login import ApiRegisterLogin
from config import log
from tool import common_assert, read_json


class TestRegisterLogin:
    # 初始化
    def setup(self):
        # 获取session对象
        self.session = requests.session()
        # 获取ApiRegisterLogin实例对象
        self.api = ApiRegisterLogin(self.session)

    # 结束
    def teardown(self):
        # 关闭session
        self.session.close()

    # 1，图片验证码接口测试
    @pytest.mark.parametrize("random,expect_code", read_json("register_login.json", "img_code"))
    def test01_img_code(self, random, expect_code):
        try:
            result = self.api.api_img_code(random)
            log.info("图片验证码接口测试结果为：{}".format(result.status_code))
            common_assert(result, status_code=expect_code)
        except Exception as e:
            # 捕获异常
            log.error(e)
            # 抛出异常
            raise

    # 2，短信验证码接口测试
    def test02_phone_code(self, phone=13332213448, imgcode=888888, expect_json="成功"):
        try:
            # 1,获取图片验证码
            self.api.api_img_code(123456)
            # 2，调用手机短信接口
            result = self.api.api_phone_code(phone, imgcode)
            log.info("短信验证码接口测试结果为：{}".format(result.text))
            common_assert(result, expect_json=expect_json)
        except Exception as e:
            # 捕获异常
            log.error(e)
            # 抛出异常
            raise

    # 3,注册接口测试
    def teat03_register(self, phone=13332213448, imgCode=888888, password="test123", phone_code=666666,
                        expect_json="成功"):

        try:
            # 1,获取图片验证码
            self.api.api_img_code(123456)
            # 2，调用手机短信接口
            self.api.api_phone_code(phone, imgCode)
            # 3，调用注册接口
            result = self.api.api_register(phone, password, verifcode=imgCode, phone_code=phone_code)
            common_assert(result, expect_json=expect_json)
        except Exception as e:
            # 捕获异常
            print("错误", e)
            # 抛出异常
            raise

    # 4，登录接口测试
    def test04_login(self, phone="13332213448", password="test123", expect_json="成功"):
        try:
            result = self.api.api_login(phone, password)
            common_assert(result, expect_json=expect_json)
        except Exception as e:
            # 捕获异常
            print("错误", e)
            # 抛出异常
            raise

    # 5，查询登陆状态接口测试
    def test05_login_status(self, status="登录", text="OK"):
        try:
            if status == "登录":
                # 调用登录
                self.api.api_login("13332213448", "test123")
            # 查询调用登录状态
            result = self.api.api_login_status()
            common_assert(result, text=text)
        except Exception as e:
            # 捕获异常
            print("错误", e)
            # 抛出异常
            raise
